package com.jiantong.user.impl.service;

import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.enums.BreedFactoryIsScale;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.impl.dao.BreedFactoryDao;
import com.jiantong.user.impl.dao.UserDao;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.User;
import com.jiantong.user.service.BreedFactoryReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.PageInfo;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 养殖档案-养殖地图
 * Created by mz03 on 2017/3/22.
 * zyp
 */
@Slf4j
@Service
@RpcProvider
public class BreedFactoryReadServiceImpl implements BreedFactoryReadService{

    /*
    private final UserDao userDao;
    private final UserProfileDao userProfileDao;
     */

    private final UserDao userDao;
    private final BreedFactoryDao breedFactoryDao;

    @Autowired
    public BreedFactoryReadServiceImpl(BreedFactoryDao breedFactoryDao,UserDao userDao) {
        this.userDao = userDao;
        this.breedFactoryDao = breedFactoryDao;
    }


    /**
     * 养殖档案-养殖地图
     * @param id 主键id
     * @return BreedRecord 对象
     */
    @Override
    public Response<BreedFactory> findById(Long id) {
        try {
            BreedFactory breedRecord = breedFactoryDao.findById(id);
            if (breedRecord == null) {
                log.error("breedReport(id={}) is not found", id);
                return Response.fail("breedReport.not.found");
            }
            return Response.ok(breedRecord);
        } catch (Exception e) {
            log.error("failed to find breedReport(id={}), cause:{}", id, Throwables.getStackTraceAsString(e));
            return Response.fail("breedReport.find.fail");
        }
    }
    /**
     * 养殖档案-养殖地图
     * @param pageNo   页码
     * @param pageSize 条数
     * @param status   状态
     * @return Paging<BreedRecord>
     */
    @Override
    public Response<Paging<BreedFactory>> pagingBreedRecord(Integer pageNo, Integer pageSize, Integer status) {
            try {
                PageInfo pageInfo = new PageInfo(pageNo, pageSize);
                Map<String, Object> criteria = Maps.newHashMap();
                if (status != null) {
                    criteria.put("status", status);
                }
                return Response.ok(breedFactoryDao.pagingByRegion(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
            } catch (Exception e) {
                log.error("failed to find breedFactory(status={}), cause:{}", status, Throwables.getStackTraceAsString(e));
                return Response.fail("breedFactory.find.fail");
            }
    }

    /**
     * 养殖档案-养殖地图
     * 根据状态status查询所有
     * @param status 状态
     * @return List<BreedRecord> 对象
     *
     */
    @Override
    public Response<List<BreedFactory>> findByStatus(Integer status) {
        try {
            Map<String, Object> criteria = Maps.newHashMap();
            LoginUser loginUser = UserUtil.getCurrentUser();
            List<Long> breedFactoryIds = loginUser.getBreedFactoryIds();
            criteria.put("breedFactoryIds",breedFactoryIds);
            if(status != null){
                criteria.put("status",status);
            }
            criteria.put("isScale",1);
            return Response.ok(breedFactoryDao.findByStatus(criteria));
        }catch (Exception e){
            log.error("find breedFactory by status:{} fail,cause:{}",status,Throwables.getStackTraceAsString(e));
            return Response.fail("find.breedFactory.fail");
        }
    }

    @Override
    public Response<List<BreedFactory>> findByStatus1(Integer status) {
        try {
            Map<String, Object> criteria = Maps.newHashMap();
            if(status != null){
                criteria.put("status",status);
            }
//            criteria.put("isScale",1);
            return Response.ok(breedFactoryDao.findByStatus1(criteria));
        }catch (Exception e){
            log.error("find breedFactory by status:{} fail,cause:{}",status,Throwables.getStackTraceAsString(e));
            return Response.fail("find.breedFactory.fail");
        }
    }

    /**
     * 关键字查询,根据养殖场\农场主名\地区 查询findByKeyword
     *
     * @param keyword
     * @return List<BreedRecord>
     */
    @Override
    public Response<List<BreedFactory>> findByKeyword(String keyword) {
        try {
            Map<String, Object> criteria = Maps.newHashMap();
            if(keyword != null){
                criteria.put("keyword",keyword);
            }
            return Response.ok(breedFactoryDao.findByKeyword(criteria));
        }catch (Exception e){
            log.error("find breedFactory by keyword:{} fail,cause:{}",keyword,Throwables.getStackTraceAsString(e));
            return Response.fail("find.breedFactory.fail");
        }
    }

    /**
     * 根据user_id查询对应的用户基础信息
     * try {
         BreedFactory breedRecord = breedFactoryDao.findById(id);
         if (breedRecord == null) {
         log.error("breedReport(id={}) is not found", id);
         return Response.fail("breedReport.not.found");
         }
         return Response.ok(breedRecord);
         } catch (Exception e) {
         log.error("failed to find breedReport(id={}), cause:{}", id, Throwables.getStackTraceAsString(e));
         return Response.fail("breedReport.find.fail");
     }
     */
    @Override
    public Response<User> findByBreedFactoryUserId(Long userId){
        try{
            User user = userDao.findById(userId);
            if (user == null){
                log.error("user (id={}) is not found",userId);
                return  Response.fail("user.not.found");
            }
            return  Response.ok(user);
        } catch (Exception e){
            log.error("failed to find user ");
            return Response.fail("yyy");
        }
    }

    /**
     * 根据ID查询user_id
     *
     * @param id
     */
    @Override
    public Response<Long> findUserIdById(Long id) {
        try{
            Long useId = breedFactoryDao.findUserIdById(id);
            if (useId == null){
                log.error("userId (id = {}) is not found",id);
                return Response.fail("useId.not.found");
            }
            return Response.ok(useId);
        } catch (Exception e){
            log.error("fainled to find userId");
            return Response.fail("find.userId.fail");
        }

    }

    /**
     * 测试: 根据ID查询一个user
     *
     * @param id
     */
    @Override
    public Response<User> findUserById(Long id) {
        try{
            User user = userDao.findById(id);
            if (user == null){
                log.error("fainled to find user by id = {}",id);
                return Response.fail("user.not.found");
            }
            return Response.ok(user);
        } catch (Exception e){
            log.error("fainled to find user");
            return Response.fail("find.user.fail");
        }
    }

    /**
     * 根据一组id分页查询出一组BreedFactory
     */
    @Override
    public Response<List<BreedFactory>> findBreedFactoryDtoByIds(List<Long> ids) {

           return  Response.ok(breedFactoryDao.findByIds(ids));



    }

    /**
     * 根据关键字匹配农场名或地区,分页查询
     *
     * @param pageNo
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public Response<Paging<BreedFactory>> pagingBreedRecordByKeyword(Integer pageNo, Integer pageSize, String keyword) {
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            Map<String, Object> criteria = Maps.newHashMap();
            LoginUser loginUser = UserUtil.getCurrentUser();
            List<Long> breedFactoryIds = loginUser.getBreedFactoryIds();
            criteria.put("breedFactoryIds",breedFactoryIds);
            if (keyword != null) {
                if(keyword.equals("散户")){
                    criteria.put("keyword2","1");
                }else {
                    criteria.put("keyword2", keyword);
                    criteria.put("excludeOne","1");
                }
                criteria.put("keyword", keyword);

            }
            return Response.ok(breedFactoryDao.pagingBreedRecord(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        } catch (Exception e) {
            log.error("failed to find BreedFactory(keyword={}), cause:{}", keyword, Throwables.getStackTraceAsString(e));
            return Response.fail("BreedRecord.find.fail");
        }
    }

    /**
     * 根据一组user_id查询出来一组养殖场
     *
     * @param user_ids
     */
    @Override
    public Response<List<BreedFactory>> findByUser_id(List<Long> user_ids) {
        try {
            List<BreedFactory> list = breedFactoryDao.findByUser_id(user_ids);
            if (list == null){
                log.error("failed to find user by id = {}",user_ids);
                return Response.fail("breedFactorys.not.found");
            }
            return Response.ok(list);
        }catch (Exception e){
            log.error("failed to find BreedFactory(user_id={}), cause:{}", user_ids, Throwables.getStackTraceAsString(e));
            return Response.fail("BreedRecord.find.fail");
        }
    }

    /**
     * 根据省,市查询养殖场
     *
     * @param provinceId
     * @param cityId
     */
    @Override
    public Response<List<BreedFactory>> findByCityId(Long provinceId, Long cityId) {

        try {
                Map<String, Object> criteria = Maps.newHashMap();
                if (provinceId != null && cityId !=null) {
                    criteria.put("provinceId", provinceId);
                    criteria.put("cityId", cityId);
                }
                List<BreedFactory> breedFactoryList = breedFactoryDao.findByCityId(criteria);
                if (breedFactoryList == null){
                    log.error("failed to find breedFactoryList by provinceId = {}; cityId = {}",provinceId,cityId);
                    return Response.fail("breedFactoryList.not.found");
                }
                return Response.ok(breedFactoryList);
            }catch (Exception e){
                log.error("failed to find breedFactoryList by provinceId = {}; cityId = {}, cause:{}", provinceId,cityId,Throwables.getStackTraceAsString(e));
                return Response.fail("BreedRecord.find.fail");
        }
    }

    /**
     * 养殖场各个种类存栏合计 根据种类类型查询存栏合计 各个种类
     *
     * @param breedType
     * @return
     */
    @Override
    public Response<List<Integer>> findQuantityByType(Integer breedType) {
        try{
            List<Integer> list = new ArrayList<>();
            if (breedType != null &&(breedType >= 1 && breedType <= 4)) {
                Integer total  = breedFactoryDao.findStockQuantityByType(breedType);
                list.add(0,total);
                return Response.ok(list);
            }else {
                for (int i=1;i <= 4;i++){
                    Integer total  = breedFactoryDao.findStockQuantityByType(i);
                    list.add(i-1,total);
                }
            }
//            List<Integer> list = breedFactoryDao.findStockQuantityListByType();
            return Response.ok(list);
        }catch (Exception e){
            log.error("failed to find stockQuantity by breedType = {}, cause:{}", breedType,Throwables.getStackTraceAsString(e));
            return Response.fail("stockQuantity.find.fail");
        }
    }
    public Response<List<Integer>> findQuantityByType1(Integer breedType,int regionId){

        try{
            List<Integer> list = new ArrayList<>();
            if (breedType != null &&(breedType >= 1 && breedType <= 4)) {
                Integer total  = breedFactoryDao.findStockQuantityByType1(breedType,regionId);
                list.add(0,total);
                return Response.ok(list);
            }else {
                for (int i=1;i <= 4;i++){
                    Integer total  = breedFactoryDao.findStockQuantityByType1(i,regionId);
                    list.add(i-1,total);
                }
            }
//            List<Integer> list = breedFactoryDao.findStockQuantityListByType();
            return Response.ok(list);
        }catch (Exception e){
            log.error("failed to find stockQuantity by breedType = {}, cause:{}", breedType,Throwables.getStackTraceAsString(e));
            return Response.fail("stockQuantity.find.fail");
        }

    }
    @Override
    public Response<List<BreedFactory>> findByArea(Map<String, Object> map) {

        try{
            return Response.ok(breedFactoryDao.findByArea(map));
        }catch (Exception e){
            log.error("failed to find by area",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find by area");
        }
    }

    /**
     * 根据省ID...村ID..  拿到这个下面的所有养殖场
     * @param provinceId 省id
     * @param cityId 市id
     * @param regionId 区id
     * @param streetId 街道id
     * @param villageId 村庄id
     * @param isScale 是否是规模场 是否规模场,0:不是;1:是(散户之类的不是规模化养殖场)
     * @param scale 规模类型 枚举 中、大、小(散户之类的可没有规模)
     * @param breedType 养殖类型
     * @return
     */
    @Override
    public Response<List<Long>> findBreedFactoryIdsByArea(Long provinceId ,Long cityId ,
                                                          Long regionId,Long streetId,
                                                          Long villageId,Integer isScale,
                                                          Integer scale ,Integer breedType) {
        Map<String , Object> map = Maps.newHashMap();
        List<Long> breedFactoryIds = new ArrayList<>();
        if(provinceId != null){
            map.put("provinceId",provinceId);
            if(cityId != null){
                map.put("cityId",cityId);
                if(regionId != null){
                    map.put("regionId",regionId);
                    if(streetId != null){
                        map.put("streetId",streetId);
                        if(villageId != null){
                            map.put("villageId",villageId);
                        }
                    }
                }
            }
        }

        if(isScale != null){
            map.put("isScale",isScale);
        }

        if(scale != null){
            map.put("scale",scale);
        }

        if(breedType != null){
            map.put("breedType",breedType);
        }

        map.put("status",1);
        try{
            List<BreedFactory> factoryList = breedFactoryDao.findByArea(map);
            if(factoryList == null || factoryList.isEmpty()){
                log.error("failed to find by area");
                return Response.fail("failed to find by area");
            }
            for(BreedFactory breedFactory : factoryList){
                breedFactoryIds.add(breedFactory.getId());
            }
            return Response.ok(breedFactoryIds);
        }catch (Exception e){
            log.error("failed to find by area",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find by area");
        }
    }

    @Override
    public Response<Paging<BreedFactory>> pagingRetail(Integer pageNo, Integer pageSize,Integer status,Long villageId,String name) {
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            LoginUser loginUser = UserUtil.getCurrentUser();
            List<Long> ids = loginUser.getBreedFactoryIds();
            Map<String, Object> criteria = Maps.newHashMap();
            if(ids != null && !ids.isEmpty()) criteria.put("ids",ids);

            criteria.put("isScale", BreedFactoryIsScale.RETAIL.value());

            if(status != null) criteria.put("status", status);

            if(!Strings.isNullOrEmpty(name)) criteria.put("name",name);

            if(villageId != null) criteria.put("villageId",villageId);

            return Response.ok(breedFactoryDao.pagingRetail(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        } catch (Exception e) {
            log.error("failed to find BreedFactory, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("BreedRecord.find.fail");
        }
    }
    public   Response<Paging<BreedFactory>> pagingRetail(Integer pageNo, Integer pageSize,Map map){

        PageInfo pageInfo = new PageInfo(pageNo, pageSize);
        return Response.ok(breedFactoryDao.pagingRetail(pageInfo.getOffset(), pageInfo.getLimit(), map));
    }
    @Override
    public Response<List<Map<String, Object>>> sumStockQuantity(List<Long> ids) {
        try{
            Map<String,Object> map = Maps.newHashMap();
            if(ids != null && !ids.isEmpty()){
                map.put("ids",ids);
            }
            map.put("status",1);
            return Response.ok(breedFactoryDao.sumStockQuantity(map));
        }catch (Exception e){
            log.error("failed to sum stock quantity,case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to sum stock quantity");
        }
    }

    /**
     * 当前登录人拿到其管辖的所有村子
     *
     * @param ids id集合
     * @return Map<String,Object>
     */
    @Override
    public Response<List<Map<String, Object>>> allVillageByIds(List<Long> ids) {

        try{
            Map<String,Object> map = Maps.newHashMap();
            if(ids != null && !ids.isEmpty()){
                map.put("ids",ids);
            }
            map.put("status",1);//删除标志 -1:删除;  1:正常
            return Response.ok(breedFactoryDao.allVillageByIds(map));
        }catch (Exception e){
            log.error("failed to sum stock quantity,case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to sum stock quantity");
        }



    }

    public List<String> serachAllCity(){

        return breedFactoryDao.serachAllCity();
    }


    public List<String> serachAllregion(String city){

        return breedFactoryDao.serachAllregion(city);
    }




    public List<String> serachAllCity1(Map map){

        return breedFactoryDao.serachAllCity1(map);
    }


    public List<String> serachAllregion1(Map map){

        return breedFactoryDao.serachAllregion1(map);
    }
    public List<Long>  serachIdsByarea(Map map){
        return  breedFactoryDao.serachIdsByarea(map);
    }

    /**
     * 官方兽医
     *
     * @param breedFactoryIds 养殖场ids
     * @return Response<List<Long>>
     */
    @Override
    public Response<List<Long>> selectIds(List<Long> breedFactoryIds) {
        try{
            Map<String , Object> criteria = Maps.newHashMap();
            criteria.put("ids",breedFactoryIds);
            criteria.put("status",1);
            criteria.put("reputation",1);
            return Response.ok(breedFactoryDao.selectIds(criteria));
        }catch (Exception e){
            log.error("failed to select ids , case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to select ids");
        }
    }


    /**
     *  查询规模场
     * @param pageNo 页码
     * @param pageSize 每页多少
     * @return Paging<BreedFactory>
     */
    @Override
    public Response<Paging<BreedFactory>> pagingScale(Integer pageNo, Integer pageSize,Integer status,String name,List<Long> ids){
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            Map<String, Object> criteria = Maps.newHashMap();
            if(ids != null && !ids.isEmpty()) criteria.put("ids",ids);

            criteria.put("isScale", BreedFactoryIsScale.SCALE.value());

            if(status != null) criteria.put("status", status);

            if(!Strings.isNullOrEmpty(name)) criteria.put("name",name);

            return Response.ok(breedFactoryDao.pagingRetail(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        } catch (Exception e) {
            log.error("failed to find BreedFactory, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("BreedRecord.find.fail");
        }
    }

    @Override
    public Response<Paging<BreedFactory>> pagingForDocument(Integer page, Integer rows, Map<String, Object> criteria) {
        try{
            PageInfo pageInfo = new PageInfo(page,rows);

            return Response.ok(breedFactoryDao.pagingForDocument(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging breed factory , case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to paging breed factory");
        }
    }

    @Override
    public Response<List<BreedFactory>> findListForWebReport(Map<String, Object> criteria) {
        try{
            return Response.ok(breedFactoryDao.findListForWebReport(criteria));
        }catch (Exception e){
            log.error("failed to find list for web report , case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find list for web report");
        }
    }
}
